// application/service/BookService.java
package com.library.bookservice.application.service;

import com.library.bookservice.domain.model.Book;
import com.library.bookservice.domain.port.BookRepositoryPort;
import com.library.bookservice.domain.port.BookServicePort;
import com.library.bookservice.domain.exception.BookAlreadyExistsException;
import com.library.bookservice.domain.exception.BookNotFoundException;
import com.library.bookservice.domain.exception.BookNotAvailableException;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 图书服务实现
 * 处理图书相关的业务逻辑
 */
@Service
public class BookService implements BookServicePort {

    private final BookRepositoryPort bookRepository;

    public BookService(BookRepositoryPort bookRepository) {
        this.bookRepository = bookRepository;
    }

    @Override
    public Book createBook(Book book) {
        if (bookRepository.existsByIsbn(book.getIsbn())) {
            throw new BookAlreadyExistsException("ISBN为 " + book.getIsbn() + " 的图书已存在");
        }
        return bookRepository.save(book);
    }

    @Override
    public Book getBookById(Long id) {
        return bookRepository.findById(id);
    }

    @Override
    public Book getBookByIsbn(String isbn) {
        return bookRepository.findByIsbn(isbn)
                .orElseThrow(() -> new BookNotFoundException("ISBN为 " + isbn + " 的图书不存在"));
    }

    @Override
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    @Override
    public List<Book> getBooksByAuthor(String author) {
        return bookRepository.findByAuthor(author);
    }

    @Override
    public List<Book> getBooksByGenre(String genre) {
        return bookRepository.findByGenre(genre);
    }

    @Override
    public Book borrowBook(Long bookId) {
        Book book = bookRepository.findById(bookId);
        if (!book.canBorrow()) {
            throw new BookNotAvailableException("图书不可借阅");
        }
        book.borrowBook();
        return bookRepository.save(book);
    }

    @Override
    public Book returnBook(Long bookId) {
        Book book = bookRepository.findById(bookId);
        book.returnBook();
        return bookRepository.save(book);
    }

    @Override
    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }
}